/*
 * Copyright (C) 2022 KylinSoft Co., Ltd.
 *
 * This program is free software: you can redistribute it and/or modify it under
 * the terms of the GNU General Public License as published by the Free Software
 * Foundation, either version 3 of the License, or (at your option) any later
 * version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along with
 * this program. If not, see <https://www.gnu.org/licenses/>.
 */

#include "desktopwindow.h"
#include <QtPlatformHeaders/QXcbWindowFunctions>
#include <QScreen>
#include <QDBusInterface>
#include <QDebug>
#include <KWayland/Client/connection_thread.h>
#include <KWayland/Client/registry.h>
#include <KWayland/Client/surface.h>
#include <kwindowsystem.h>
#include <windowmanager/windowmanager.h>

DesktopWindow::DesktopWindow(QWindow *parent)
    : PlatformWindow(parent, false, false, KWayland::Client::PlasmaShellSurface::Role::Desktop)
{
    if (!m_isWayland) {
        QXcbWindowFunctions::setWmWindowType(this, QXcbWindowFunctions::Desktop);
    }
    this->setFlag(Qt::FramelessWindowHint);

    auto screen = this->screen();
    initScreenConnections(screen);
    connect(this, &QQuickView::screenChanged, this, &DesktopWindow::initScreenConnections);

    connect(this, &DesktopWindow::activeChanged, this, &DesktopWindow::onActiveChanged);
    QDBusConnection::sessionBus().connect(QString("org.ukui.KWin"),
                                          QString("/KWin"),
                                          QString("org.ukui.KWin"),
                                          QString("unmanageWindowActived"),
                                          this, SIGNAL(desktopIsNotActived()));
}

void DesktopWindow::onActiveChanged()
{
    if (this->isActive() || isPolkitWindowActived()) {
        return;
    }

    Q_EMIT desktopIsNotActived();
}

bool DesktopWindow::isPolkitWindowActived()
{
    using namespace kdk;
    // todo: wayland
    WId wid = KWindowSystem::activeWindow();
    KWindowInfo windInfo(wid, NET::ActiveWindow);
    int pid = windInfo.pid();
    if (m_isWayland) {
        WindowId wid = WindowManager::currentActiveWindow();
        pid = WindowManager::getPid(wid);
    }

    if (pid <= 0) {
        return false;
    }
    QString cmdLineFile = QString("/proc/%1/cmdline").arg(pid);
    QFile file(cmdLineFile);
    if (!file.open(QIODevice::ReadOnly)) {
        qWarning() << "Open " + cmdLineFile + " failed! " << file.errorString();
        return false;
    }

    QString cmdline = file.readAll();
    return cmdline.contains("polkit-ukui-authentication-agent");
}

void DesktopWindow::initScreenConnections(QScreen *screen)
{
    if (!screen) {
        qWarning() << "PlatformaWindow initScreenConnections Screen is null.";
        return;
    }
    connect(screen, &QScreen::primaryOrientationChanged, this, &DesktopWindow::updateWindowGeometry);
    connect(screen, &QScreen::geometryChanged, this, &DesktopWindow::updateWindowGeometry);
}

void DesktopWindow::updateWindowGeometry()
{
    if (!this->screen()) {
        qWarning() << "PlatformaWindow Screen is null.";
        return;
    }
    this->setGeometry(this->screen()->geometry());
    this->requestUpdate();
}
